﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Globalization;

namespace CarBloke.Pages
{
    public partial class VehicleEditPage : PhoneApplicationPage
    {
        bool _saveState = true;
        const String _nameKey = "VehicleEditPageName";
        const String _yearKey = "VehicleEditPageYear";
        const String _notesKey = "VehicleEditPageNotes";

        Vehicle _vehicle = null;
        private Boolean initialValidation = false;

        public VehicleEditPage()
        {
            InitializeComponent();

            //Application bar and application menu text must be set here explicitly.
            var saveButton = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            var cancelButton = ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            saveButton.Text = LanguageResources.Resources._save;
            cancelButton.Text = LanguageResources.Resources._cancel;    
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (_saveState)
                saveState();
            else
                clearState();
            
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);            

            string vehicleID = "";
            if (NavigationContext.QueryString.TryGetValue("vehicleID", out vehicleID))
            {
                Guid id = new Guid(vehicleID);
                _vehicle = App.LoadVehicle(id);
            }

            initalizeUserInterface();
            restoreState();
        }

        private void initalizeUserInterface()
        {
            if (_vehicle != null)
            {
                nameTextBox.Text = _vehicle.Name;
                yearTextBox.Text = _vehicle.Year.ToString();
                notesTextBox.Text = _vehicle.Notes;
            }
        }

        private void appbar_saveButton_Click(object sender, EventArgs e)
        {
            if (performValidation())
            {
                _saveState = false;

                SaveVehicle();
                NavigationService.GoBack();
            }           
        }

        private void appbar_cancelButton_Click(object sender, EventArgs e)
        {
            _saveState = false;
            NavigationService.GoBack();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            _saveState = false;
            base.OnBackKeyPress(e);
        }

        private void SaveVehicle()
        {
            Guid id = _vehicle != null ? _vehicle.ID : Guid.NewGuid();

            Vehicle vehicle = new Vehicle()
            {
                ID = id,
                Name = nameTextBox.Text,
                Year = int.Parse(yearTextBox.Text),
                Notes = notesTextBox.Text,                
            };

            App.SaveVehicle(vehicle);
        }

        private bool performValidation()
        {
            initialValidation = true;

            Boolean passedValidation = true;
            passedValidation &= validateName();
            passedValidation &= validateYear();
            return passedValidation;
        }

        private bool validateName()
        {
            Boolean passedValidation = true;
            clearWarning(nameBorder);
            if (String.IsNullOrEmpty(nameTextBox.Text))
            {
                passedValidation = false;
                setError(nameBorder);
            }

            return passedValidation;
        }

        private bool validateYear()
        {
            Boolean passedValidation = true;
            clearWarning(yearBorder);
            int year;
            if (String.IsNullOrEmpty(yearTextBox.Text) || !int.TryParse(yearTextBox.Text, out year) || year < 0)
            {
                passedValidation = false;
                setError(yearBorder);
            }

            return passedValidation;
        }


        private void nameTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (initialValidation)
            {
                validateName();
            }
        }

        private void yearTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (initialValidation)
            {
                validateYear();
            }
        }

        private void setError(Border border)
        {
            Color errorColor = Colors.Red;
            errorColor.A = 0xAA;

            border.Background = new SolidColorBrush(errorColor);
        }

        private void clearWarning(Border border)
        {
            border.Background = null;
        }

        private void nameTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            nameTextBox.Focus();
            e.Handled = true;
        }

        private void yearTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            yearTextBox.Focus();
            e.Handled = true;
        }

        private void notesTextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            notesTextBox.Focus();
            e.Handled = true;
        }

        private void saveState()
        {
            clearState(_nameKey);
            PhoneApplicationService.Current.State.Add(_nameKey, this.nameTextBox.Text);

            clearState(_yearKey);
            PhoneApplicationService.Current.State.Add(_yearKey, this.yearTextBox.Text);

            clearState(_notesKey);
            PhoneApplicationService.Current.State.Add(_notesKey, this.notesTextBox.Text);
        }

        private void restoreState()
        {
            if (true == PhoneApplicationService.Current.State.ContainsKey(_nameKey))
            {
                string s = PhoneApplicationService.Current.State[_nameKey] as string;
                if (!String.IsNullOrEmpty(s))
                {
                    this.nameTextBox.Text = s;
                }
            }

            if (true == PhoneApplicationService.Current.State.ContainsKey(_yearKey))
            {
                string s = PhoneApplicationService.Current.State[_yearKey] as string;
                if (!String.IsNullOrEmpty(s))
                {
                    this.yearTextBox.Text = s;
                }
            }

            if (true == PhoneApplicationService.Current.State.ContainsKey(_notesKey))
            {
                string s = PhoneApplicationService.Current.State[_notesKey] as string;
                if (!String.IsNullOrEmpty(s))
                {
                    this.notesTextBox.Text = s;
                }
            }
        }

        private void clearState()
        {
            clearState(_nameKey);
            clearState(_yearKey);
            clearState(_notesKey);
        }

        private void clearState(string key)
        {
            if (true == PhoneApplicationService.Current.State.ContainsKey(key))
            {
                PhoneApplicationService.Current.State.Remove(key);
            }
        }
    }
}